﻿var str = window.location.search;
var Index = str.indexOf('=');
var cid = str.substring(Index + 1);

$("#createTest").click(function () {
    createTest();
});

$("div").on("click", ".deleteTest", function () {
    var e = $(this).attr("button-Item");
    deleteTest(e);
});

$("div").on("click", ".updateTest", function () {
    var e = $(this).attr("button-Item");
    var str = window.location.href;
    console.log(str)
    var lastIndex = str.lastIndexOf('/');
    var firstIndex = str.lastIndexOf('/', lastIndex - 1);
    cid = str.substring(firstIndex + 1, lastIndex);
    window.location.assign("/Main/Add?id=" + e + "&&cid=" + cid);
});



$("div").on("click", ".editTest", function () {
    var e = $(this).attr("button-Item");
    editTest(e);
});


var answerInfo ,studentInfo ,a = 0, c = 0,testTime;
//查看答题情况
$("div").on("click", ".answerIs", function () {
    var e = $(this).attr("button-Item");
    getAnswerInfo(e);
});

var stuExamInfo;
//考试详细信息
$("div").on("click", ".examInfo",function() {
    var e = $(this).attr("button-Item");
    getExamInfo(e);
 });

//发布
$("div").on("click", ".issue", function () {
    var e = $(this).attr("button-Item");
    TestIssue(e);
});
$("div").on("click", ".shutdownIssue", function () {
    var e = $(this).attr("button-Item");
    shutdownIssue(e);
});

//新建试卷
function createTest() {
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "新建试卷"
            , closeBtn: false
            , area: ['500px', 'auto']
            , shade: 0.6
            , id: 'LAY_create' //设定一个id，防止重复弹出
            , btn: ['保存', '取消']
            , btnAlign: 'c'
            , content: ' <div class="row" style="width: 420px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                + '<div class="col-sm-12">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none">试卷名称：</span>'
                + '<input id="TestName" type="text" class= "form-control" placeholder="请输入试卷名称" >'
                + '</div>'
                + '</div>'
                + '</div>'
            , btn1: function (index, layero) {
                var tName = $("#TestName").val();
                if (tName == "") {
                    layer.msg("请输入试卷名称！");
                    return false;
                }
                var loading = layer.msg('保存中',
                    {
                        icon: 16,
                        time: 5000,
                        shade: 0.1
                    });
                $.ajax({
                    type: "POST",
                    url: "/TestPaperTbs/CreateTest",
                    data: {
                        testName: tName,
                        cid: cid
                    },
                    dataType: 'json',
                    success: function (data) {
                        layer.msg(data.msg);
                        layer.close(loading);
                        setTimeout(goto, 2000);
                    },
                    error: function (data) {
                        layer.msg(data.msg);
                    }
                });
            },
            btn2: function (index, layero) {
                layer.close(index);
            }
        });
    });
}

//删除试卷
function deleteTest(e) {
    layer.confirm('确定删除？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        var loading = layer.msg('删除中',
            {
                icon: 16,
                time: 5000,
                shade: 0.1
            });
        $.ajax({
            type: "POST",
            url: "/TestPaperTbs/DeleteTest",
            data: {
                testPaperTbId: e
            },
            dataType: 'json',
            success: function (data) {
                layer.msg(data.msg);
                layer.close(loading);
                setTimeout(goto, 2000);
            },
            error: function (data) {
                layer.msg(data.msg);
            }
        });
    }, function () {


    });
}

//修改试卷
function editTest(e) {
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "试卷信息"
            , closeBtn: false
            , area: ['500px', 'auto']
            , shade: 0.6
            , id: 'LAY_details' //设定一个id，防止重复弹出
            , btn: ['保存', '取消']
            , btnAlign: 'c'
            , moveType: 0 //拖拽模式，0或者1
            , content: ' <div class="row" style="width: 420px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                + '<div class="col-sm-12">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none"> 试卷名称：</span>'
                + '<input id="ExamName" type="text" class= "form-control" placeholder="请输入试卷名称" >'
                + '</div>'
                + '</div>'
                + '<div class="col-sm-12" style="margin-top: 10px">'
                + '<div class="input-group">'
                + '<span class="input-group-addon" style="background:white;border:none">出卷人：</span>'
                + '<input id="Creator" type="text" class= "form-control" >'
                + '</div>'
                + '</div>'
                + '</div>'
            , btn1: function (index, layero) {
                var tName = $("#ExamName").val();
                var tCreator = $("#Creator").val();
                if (tName == "" || tCreator == "") {
                    layer.msg("请输入试卷名称和出卷人");
                    return false;
                }
                var loading = layer.msg('保存中',
                    {
                        icon: 16,
                        time: 5000,
                        shade: 0.1
                    });
                $.ajax({
                    type: "POST",
                    url: "/TestPaperTbs/EditTest",
                    data: {
                        testPaperTbId: e,
                        testName: tName,
                        creator: tCreator
                    },
                    dataType: "json",
                    success: function (data) {
                        layer.msg(data.msg);
                        layer.close(loading);
                        setTimeout(goto, 2000);
                    },
                    error: function (data) {
                        layer.msg(data.msg);
                    }
                });
            },
            btn2: function (index) {
                layer.close(index);
            }
        });
        const a = $('#TestName_' + e).text();
        const b = $('#Creator_' + e).text();
        $("#ExamName").attr("value", a);
        $("#Creator").attr("value", b);
    });
}
var closeInterval;
//查看答题情况
function answerIs() {
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "答题情况"
            , closeBtn: false
            , area: ['70%', '82%']
            , shade: 0.6
            , id: 'LAY_answerIs' //设定一个id，防止重复弹出
            , btn: ['确定']
            , btnAlign: 'c'
            , content: ' <div class="row" style="width:900px;height:430px;padding:10px 30px;background-color: #FAFAFA !important;">'
                + '<div id="pageContent" class="layui-card" style="width: 500px; height: 400px; margin: 0 auto;float:left;" ></div>'
                + '<div class="layui-card" style="width:280px;height:400px;float:right;background-color:white;margin:0 10px 0 50px;">'
                + '<h4 style="margin:20px;">考试开始时间</h4><div style="height:60px;font-size:24px;text-align:center;" id="startTime"></div>'
                + '<h4 style="margin:20px;">考试结束时间</h4><div style="height:60px;font-size:24px;text-align:center;" id="endTime"></div>'
                + '<h4 style="margin:20px;">累积考试时间</h4><div style="height:60px;font-size:35px;text-align:center;color:#ec7724" id="nowTime"></div>'
                +'</div> '
                + '</div>'
            , btn1: function (index, layero) {
                layer.close(index);
                clearInterval(closeInterval);
            }
        });
        var title = {
            text: '考试情况'
        };
        var plotOptions = {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        };
        var series = [{
            type: "pie",
            name: "人数",
            data: [
                ["未参加考试", a],
                {
                    name: "已提交",
                    y: c
                }
            ]
        }];
        var json = {};
        json.title = title;
        json.series = series;
        json.plotOptions = plotOptions;
        $('#pageContent').highcharts(json);
        $('#startTime').text(testTime.startTime);
        $('#endTime').text(testTime.endTime);
        //clearInterval(closeInterval);
        //gainTime(testTime.startTime);

        var startTime = new Date(testTime.startTime).getTime();
        var s = 0;
        var m = 0;
        var h = 0;
        var d = 0;
        var closeInterval = setInterval(seckill, 1000);
        function seckill() {
            const nowTime = new Date();
            const remaining = parseInt((nowTime.getTime() - startTime) / 1000);

            if (remaining > 0) {
                d = parseInt(remaining / 86400);
                h = parseInt((remaining / 3600) % 24);
                m = parseInt((remaining / 60) % 60);
                s = parseInt(remaining % 60);

                d = d < 10 ? '0' + d : d;
                h = h < 10 ? '0' + h : h;
                m = m < 10 ? '0' + m : m;
                s = s < 10 ? '0' + s : s;
            } else {
                clearInterval(closeInterval);
                d = h = m = s = "00";
            }
            $("#nowTime").text(d + ":" + h + ":" + m + ":" + s);
        }
        
    });
}


//function gainTime(time) {
//    var startTime = new Date(time).getTime();
//    var s = 0;
//    var m = 0;
//    var h = 0;
//    var d  = 0;
//    var closeInterval = setInterval(seckill, 1000);
//    function seckill() {
//        const nowTime = new Date();
//        const remaining = parseInt((nowTime.getTime() - startTime) / 1000);
       
//        if (remaining > 0) {
//            d = parseInt(remaining / 86400);
//            h = parseInt((remaining / 3600) % 24);
//            m = parseInt((remaining / 60) % 60);
//            s = parseInt(remaining % 60);

//            d = d < 10 ? '0' + d : d;
//            h = h < 10 ? '0' + h : h;
//            m = m < 10 ? '0' + m : m;
//            s = s < 10 ? '0' + s : s;
//        } else {
//            clearInterval(closeInterval);
//            d = h = m = s = "00";
//        }
//        $("#nowTime").text(d + ":" + h + ":" + m + ":" + s); 
//    }
//}

//获取答题情况
function getAnswerInfo(e) {
    $.ajax({
        async: false,
        url: '/TestPaperTbs/ResultAnswer',
        type: 'get',
        data: {
            testId: e
        },
        dataType: 'json',
        timeout: 5000,
        success: function (data) {
            answerInfo = data.Answer;
            studentInfo = data.student;
            testTime = data.TestTime;
            a = studentInfo - answerInfo;
            c = answerInfo;
            answerIs();
        },
    });
}

var AllClass;
//发布页面
function TestIssue(e) {
    layui.use(['layer','laydate'], function () {
        var laydate = layui.laydate;
        layer.open({
            type: 1
            , title: "发布试卷"
            , closeBtn: false
            , area: ['30%', 'auto']
            , shade: 0.6
            , id: 'LAY_details' //设定一个id，防止重复弹出
            , btn: ['保存', '取消']
            , btnAlign: 'c'
            , moveType: 0 //拖拽模式，0或者1
            , content:
                //input radio 有bug
                `<div class="layui-form layui-form-pane" style="margin:10px" >
                    <div class="layui-form-item">
                        <label class="layui-form-label">试卷名称</label>
                        <div class="layui-input-block">
                          <input type="text" class="layui-input"  id="TestName" disabled="disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">考试说明</label>
                        <div class="layui-input-block">
                          <input type="text" class="layui-input" id="notes" placeholder="考试说明">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">考试班级</label>
                        <div class="layui-input-block" id="curriculum">
                          
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">开始时间</label>
                        <div class="layui-input-block">
                         <input type="text" id="StartTime" class="layui-input TimeItem" placeholder="yyyy-MM-dd" />
                          
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">结束时间</label>
                        <div class="layui-input-block">
                        <input type="text" id="EndTime"  class="layui-input TimeItem" placeholder="请选择" />

                        </div>
                    </div>
                    <div class="layui-form-item" >
                        <label class="layui-form-label">限时</label>
                        <div class="layui-input-inline" >
                        <input type="number" min="0" onkeyup="this.value=this.value.replace(/\D/g,'')" id="OnTime" style="width:60px;display:inline-block" class="layui-input" placeholder="分钟" value="0" />
                        <span style="color:gray">分钟,0为不限时间</span>
                        </div>
                    </div>
                </div>`
            , btn1: function (index, layero) {
                var loading = layer.msg('保存中',
                    {
                        icon: 16,
                        time: 5000,
                        shade: 0.1
                    });
                var classes = new Array();
                var notes = $("#notes").val();
                for (let a in AllClass) {
                    var item =$("#class_" + AllClass[a].classId).attr("class");
                    if (item == "layui-btn layui-btn-normal") {
                        classes.push(AllClass[a].classId);
                    }
                }
                //console.log(classes);
                var start = $("#StartTime").val();
                var end = $("#EndTime").val();
                var onTime = $("#OnTime").val();
                $.ajax({
                    type: "POST",
                    url: "/TestPaperTbs/PutOut",
                    data: {
                        Id: e,
                        notes: notes,
                        classes:classes,
                        start: start,
                        end: end,
                        onTime: onTime
                    },
                    dataType: "json",
                    success: function (data) {
                        layer.close(loading);
                        layer.msg(data.msg);
                        setTimeout(goto, 2000);
                    },
                    error: function (data) {
                        layer.msg("参数错误");
                    }
                });
            },
            btn2: function (index, layero) {
                layer.close(index);
            }
        });
        var a = $('#TestName_' + e).text();
        var b = getNowDate();
        $("#TestName").val(a);
        $("#StartTime").attr("value", b);
        if (cid == "") {
            var str = window.location.href;
            var lastIndex = str.lastIndexOf('/');
            var firstIndex = str.lastIndexOf('/', lastIndex-1);
            cid = str.substring(firstIndex + 1, lastIndex);
            //console.log("开始:" + firstIndex + ",结束：" + lastIndex + "结果：" + cid)
        }
        findClass(cid);
        //日期时间选择器
       
        lay('.TimeItem').each(function () {
            laydate.render({
                elem: this,
                type: 'datetime',
                min:0,
                trigger: 'click'
            });
        });
    });
}
//查询班级
function findClass(e) {
    var indexFirst = layer.load(1, { time: 10 * 1000, shade: false });
    $.ajax({
        type: "POST",
        url: "/TestPaperTbs/FindClasses",
        data: {
            curriculumId: e
        },
        dataType: 'json',
        success: function (data) {
            AllClass = data;
            showClass();
            layer.close(indexFirst);

        }, error: function (data) {
            layer.msg(data.msg);
            layer.close(indexFirst);
        }
    })
}

//显示班级
function showClass() {
    var str = "";
    for (let a in AllClass) {
        str += `<button type='button' class='layui-btn layui-btn-primary' onclick="onclickBtn(` + AllClass[a].classId + `)"  id='class_` + AllClass[a].classId + `'>` + AllClass[a].className + `</button>`;
    }
    $("#curriculum").html(str);
}

function onclickBtn(e) {
    if ($("#class_"+e).attr("class") == "layui-btn layui-btn-primary") {
        $("#class_" + e).attr("class", "layui-btn layui-btn-normal");
    } else {
        $("#class_" + e).attr("class", "layui-btn layui-btn-primary");
    }
}

//结束发布
function shutdownIssue(e) {
    layer.confirm('确定结束发布？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        var loading = layer.msg('保存中',
            {
                icon: 16,
                time: 5000,
                shade: 0.1
            });
        $.ajax({
            type: "POST",
            url: "/TestPaperTbs/ShoutDownIssue",
            data: {
                testPaperTbId: e
            },
            dataType: 'json',
            success: function (data) {
                layer.msg(data.msg);
                layer.close(loading);
                setTimeout(goto, 2000);
            },
            error: function (data) {
                layer.msg(data.msg);
            }
        });
    }, function () {


    });
}

var i = 0;
//获取考试详细信息
function getExamInfo(e) {
    $.ajax({
        async: false,
        url: '/TestPaperTbs/ResultExamInfo',
        type: "post",
        data: {
            testId: e
        },
        dataType: "json",
        success: function (data) {
            var exchange, className = "", a = 0, b = 0, c = 0, d = 0, e = 0;
            for (var i = 0; i < data.length; i++) {
                exchange = false;
                for (var j = data.length-1; j > i; j--) {
                    if (data[j].score < data[j - 1].score) {
                        var stu = data[j - 1];
                        data[j - 1] = data[j];
                        data[j] = stu;
                        exchange = true;
                    }
                }
                if (!exchange) break;
            }
            stuExamInfo = data;
            for (var i = 0; i < data.length; i++) {
                data[i].score < 90 ? (data[i].score < 80 ? (data[i].score < 70 ? (data[i].score < 60 ? a++ : b++) : c++) : d++) : e++;
            }
            examInfo(className,a,b,c,d,e);
        }
    });
}

//显示考试详细信息
function examInfo(className, a, b, c, d, e) {

    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "答题情况"
            , closeBtn: false
            , area: ['70%', '82%']
            , shade: 0.6
            , id: 'LAY_examInfo' //设定一个id，防止重复弹出
            , btn: ['确定']
            , btnAlign: 'c'
            , content: ' <div class="row" style="width: 900px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;background-color: #FAFAFA !important;">'
                + '<div id="examAnswerIs">'
                + '<div id="container" class="layui-card" style="width: 600px; height: 400px; margin: 0 auto;float:left" ></div>'
                + '<div class="layui-card ranking" style="width:200px; height:400px; margin:0 auto;float:right;"></div>'
                + '</div> '
                + '</div>'
            , btn1: function (index, layero) {
                layer.close(index);
            },
        });
        var chart = {
            type: 'column'
        };
        var title = {
            text: '第一次考试情况'
        };
        var xAxis = {
            categories: ['60以下', '60~70', '70~80', '80~90', '90~100'],
            crosshair: true
        };
        var yAxis = {
            min: 0,
            title: {
                text: '分数段（人数）'
            }
        };
        var tooltip = {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:f} 人</b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        };
        var plotOptions = {
            column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
        };
        var credits = {
            enabled: false
        };

        var series = [{
            name: className,
            data: [a, b, c, d, e]
        }];

        var json = {};
        json.chart = chart;
        json.title = title;
        json.tooltip = tooltip;
        json.xAxis = xAxis;
        json.yAxis = yAxis;
        json.series = series;
        json.plotOptions = plotOptions;
        json.credits = credits;
        $('#container').highcharts(json);
        var text = '<div><h4 class="layui-card-header" style = "padding: 0 20px 10px 20px;" > 成绩排名</h4 > '
            + '<div class="layui-card-body">'
            + '<div class="layui-collapse" lay-accordion="">';
        for (var item in stuExamInfo) {
            text += '<div class="layui-colla-item">'
                 + '<h2 class="layui-colla-title">' + stuExamInfo[item].stu + '：' + stuExamInfo[item].score+'分</h2 > '
                 +'<div class="layui-colla-content">内容区域</div>'
                 +'</div>';
        }
        text +='</div></div></div>'
        $('.ranking').html(text);
        return;
        //layui.use(['dropdown', 'util', 'layer'], function () {
        //    var element = layui.element;
        //    var layer = layui.layer;
        //    element.render();

        //    //监听折叠
        //    element.on('collapse(test)', function (data) {
        //        layer.msg('展开状态：' + data.show);
        //    });
        //});
    });
}

//function controlTime(e) {
//    if (e === 1) {
//        $("#OnTime").removeAttr("hidden");
//    } else {
//        $("#OnTime").val("");
//        $("#OnTime").attr("hidden", "hidden");
//    }
//}
////时间限制
//$("div").on("click", "#LineTime", function () {
//    $("#OnTime").removeAttr("hidden");
//});
//$("div").on("click", "#noLineTime", function () {
//    $("#OnTime").attr("hidden", "hidden");
//});

//页面刷新
function goto() {
    window.location.reload();
}